﻿using FolderSelect;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MangaReader
{

    public partial class Form1 : Form
    {

        string store1, store2, store3, store4;
        //MODIFIED--------------------------------
        Boolean color = true; // set default color to black
        public Form1(string[] path)
        {
            InitializeComponent();
            if (path != null && path.Length > 0)
            {
                createReader(System.IO.Path.GetFullPath(path[0]));
            }
        }

        public List<String> convert(List<String> s)
        {
            List<String> e = new List<string>();
            foreach(String t in s)
            {
            Uri u = new System.Uri(t);
            e.Add(u.AbsoluteUri);
            }
            return e;
        }

        public String convert(String s)
        {
            Uri u = new System.Uri(s);
            return u.ToString();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                if (radioButtonBlack.Checked)
                {
                    color = true;
                }
                else color = false;
                string startupPath = Application.StartupPath;
                using (FolderBrowserDialog dialog = new FolderBrowserDialog())
                {
                    //dialog.Description = "Open a folder which contains the xml output";
                    //dialog.ShowNewFolderButton = false;
                    //dialog.RootFolder = Environment.SpecialFolder.MyComputer;
                    String link = System.IO.File.ReadAllText("Resources/data.txt");
                    
                    //if (dialog.ShowDialog() == DialogResult.OK)
                    var fsd = new FolderSelectDialog();
                    fsd.Title = "What to select";
                    fsd.InitialDirectory = link;
                    if (fsd.ShowDialog(IntPtr.Zero))
                    {
                        //MODIFIED--------------------------------
                        createReader(fsd.FileName);
                    }
                }
            }
            catch (Exception exc)
            {
                MessageBox.Show("Import failed because " + exc.Message + " , please try again later.");
            }
        }
        //MODIFIED--------------------------------
        private void createReader(String path) //fsd.FileName -> path
        {
            List<String> files, folders, top;
            String code = "", code1 = "", code2 = "";
            //MODIFIED--------------------------------
            System.IO.File.WriteAllText(Application.StartupPath + @"\Resources\data.txt", path); //Relative path modified
            top = Directory.GetDirectories(path, "*", SearchOption.TopDirectoryOnly).ToList();

            code1 += "changeBg(" + color.ToString().ToLower() + ");";
            store1 = txtOpenChaptersList.Text.ToString().ToLower();
            code2 += "bindHotkeys('c', \"" + store1 + "\"); ";
            store2 = txtOpenSettings.Text.ToString().ToLower();
            code2 += "bindHotkeys('m', \"" + store2 + "\"); ";
            store3 = txtGoPrevChap.Text.ToString().ToLower();
            code2 += "bindHotkeys('p', \"" + store3 + "\"); ";
            store4 = txtGoNextChap.Text.ToString().ToLower();
            code2 += "bindHotkeys('n', \"" + store4 + "\"); ";

            code += "display(\"";
            files = Directory.GetFiles(path, "*.*", SearchOption.TopDirectoryOnly).Where(file => file.ToLower().EndsWith("jpg") || file.ToLower().EndsWith("png") || file.ToLower().EndsWith("jpeg") || file.ToLower().EndsWith("gif") || file.ToLower().EndsWith("bmp") || file.ToLower().EndsWith("thm") || file.ToLower().EndsWith("tif")).ToList();
            String o = convert(path);
            code += "<div name='" + o.Substring(o.LastIndexOf('/') + 1) + "'>";
            files = convert(files);
            foreach (String x in files)
            {
                code += "<input value='" + x.Replace("'", @"&#39;") + "'/>";
            }
            code += "</div>";
            foreach (String t in top)
            {
                files = Directory.GetFiles(t, "*.*", SearchOption.TopDirectoryOnly).Where(file => file.ToLower().EndsWith("jpg") || file.ToLower().EndsWith("png") || file.ToLower().EndsWith("jpeg") || file.ToLower().EndsWith("gif") || file.ToLower().EndsWith("bmp") || file.ToLower().EndsWith("thm") || file.ToLower().EndsWith("tif")).ToList();
                String f = convert(t);
                code += "<div name='" + f.Substring(f.LastIndexOf('/') + 1) + "'>";
                files = convert(files);
                foreach (String s in files)
                {
                    code += "<input value='" + s.Replace("'", @"\'") + "'/>";
                }
                code += "</div>";
                folders = Directory.GetDirectories(t, "*", SearchOption.TopDirectoryOnly).ToList();
                foreach (String c in folders)
                {
                    files = Directory.GetFiles(c, "*.*", SearchOption.TopDirectoryOnly).Where(file => file.ToLower().EndsWith("jpg") || file.ToLower().EndsWith("png") || file.ToLower().EndsWith("jpeg") || file.ToLower().EndsWith("gif") || file.ToLower().EndsWith("bmp") || file.ToLower().EndsWith("thm") || file.ToLower().EndsWith("tif")).ToList();
                    String a = convert(c);
                    code += "<div name='" + a.Substring(a.LastIndexOf('/') + 1) + "'>";
                    files = convert(files);
                    foreach (String v in files)
                    {
                        code += "<input value='" + v.Replace("'", @"\'") + "'/>";
                    }
                    code += "</div>";
                }
                code += "</div>";
            }
            code += "</div>\");";
            //MODIFIED-------------------------------- Add "application.startuppath +" and "\" before relative path
            string[] header = System.IO.File.ReadAllLines(Application.StartupPath + @"\Resources\header.txt");
            System.IO.File.WriteAllLines(Application.StartupPath + @"\reader.html", header);
            String[] body1 = System.IO.File.ReadAllLines(Application.StartupPath + @"\Resources\body1.txt");
            System.IO.File.AppendAllLines(Application.StartupPath + @"\reader.html", body1);
            System.IO.File.AppendAllText(Application.StartupPath + @"\reader.html", code1);
            System.IO.File.AppendAllText(Application.StartupPath + @"\reader.html", code2);
            System.IO.File.AppendAllText(Application.StartupPath + @"\reader.html", code);
            String[] body2 = System.IO.File.ReadAllLines(Application.StartupPath + @"\Resources\body2.txt");
            System.IO.File.AppendAllLines(Application.StartupPath + @"\reader.html", body2);
            System.Diagnostics.Process.Start(Application.StartupPath + @"\reader.html"); //add a @ character
        }

        private void txtOpenChaptersList_KeyPress(object sender, KeyPressEventArgs e)
        {
            char ch = e.KeyChar;
            if (!Char.IsLetter(ch))
            {
                e.Handled = true;
                MessageBox.Show("Please enter a value from A-Z!");

            }
            else if (e.KeyChar.ToString() == store2 || e.KeyChar.ToString() == store3 || e.KeyChar.ToString() == store4)
            {
                e.Handled = true;
                MessageBox.Show("Choose difference Character!");
            }
            else {txtOpenChaptersList.Clear(); }
        }

        private void txtOpenSettings_KeyPress(object sender, KeyPressEventArgs e)
        {
            char ch = e.KeyChar;
            if (!Char.IsLetter(ch))
            {
                e.Handled = true;
                MessageBox.Show("Please enter a value from A-Z!");

            }
            else if (e.KeyChar.ToString() == store1 || e.KeyChar.ToString() == store3 || e.KeyChar.ToString() == store4)
            {
                e.Handled = true;
                MessageBox.Show("Choose difference Character!");
            }
            else {txtOpenSettings.Clear(); }
        }

        private void txtGoPrevChap_KeyPress(object sender, KeyPressEventArgs e)
        {
            char ch = e.KeyChar;
            if (!Char.IsLetter(ch))
            {
                e.Handled = true;
                MessageBox.Show("Please enter a value from A-Z!");

            }
            else if (e.KeyChar.ToString() == store1 || e.KeyChar.ToString() == store2 || e.KeyChar.ToString() == store4)
            {
                e.Handled = true;
                MessageBox.Show("Choose difference Character!");
            }
            else {txtGoPrevChap.Clear(); }
        }

        private void txtGoNextChap_KeyPress(object sender, KeyPressEventArgs e)
        {
            char ch = e.KeyChar;
            if (!Char.IsLetter(ch))
            {
                e.Handled = true;
                MessageBox.Show("Please enter a value from A-Z!");

            }
            else if (e.KeyChar.ToString() == store1 || e.KeyChar.ToString() == store2 || e.KeyChar.ToString() == store3)
            {
                e.Handled = true;
                MessageBox.Show("Choose difference Character!");
            }
            else {txtGoNextChap.Clear(); }
        }

        private void radioButtonBlack_CheckedChanged(object sender, EventArgs e)
        {
            if (radioButtonBlack.Checked)
            {
                color = true;
            }
        }

        private void radioButtonWhite_CheckedChanged(object sender, EventArgs e)
        {
            if (radioButtonWhite.Checked)
            {
                color = false;
            }
        }

        private void btnLastChoice_Click(object sender, EventArgs e)
        {
            try
            {
                System.Diagnostics.Process.Start("reader.html");
            }
            catch
            {
                MessageBox.Show("No recent action found. Please open new folder of manga!");
            }
        }

        private void btnAddContext_Click(object sender, EventArgs e)
        {
            String path, code;
            path = Application.ExecutablePath.Replace(@"\", @"\\");
            code = "Windows Registry Editor Version 5.00" + Environment.NewLine + Environment.NewLine;
            code += "[HKEY_CLASSES_ROOT\\Directory\\shell\\View with MangaReader\\command]" + Environment.NewLine;
            code += "@=\"" + path + " %1\"";
            System.IO.File.WriteAllText("addContext.reg", code);
            System.Diagnostics.Process.Start("addContext.reg");
        }

        private void btnDelContext_Click(object sender, EventArgs e)
        {
            String path, code;
            path = Application.ExecutablePath.Replace(@"\", @"\\");
            code = "Windows Registry Editor Version 5.00" + Environment.NewLine + Environment.NewLine;
            code += "[-HKEY_CLASSES_ROOT\\Directory\\shell\\View with MangaReader]" + Environment.NewLine;
            System.IO.File.WriteAllText("removeContext.reg", code);
            System.Diagnostics.Process.Start("removeContext.reg");
        }
    }
}